package com.example.takeaway.websocket;

import cn.hutool.core.net.url.UrlQuery;
import cn.hutool.core.util.CharsetUtil;
import com.alibaba.fastjson.JSON;
import com.example.takeaway.constant.CacheNames;
import com.example.takeaway.model.bo.UserAccount;
import com.example.takeaway.util.RedisUtil;

import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.List;
import java.util.Map;

/**
 * @author 邢晨旭
 * {@code @date} 2023/10/27
 */
public class WsConfigurator extends ServerEndpointConfig.Configurator {

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        Map<String, List<String>> parameterMap = request.getParameterMap();
        List<String> tokens = parameterMap.get("token");
        sec.getUserProperties().put("check", false);
        if (tokens != null && tokens.size() > 0) {
            String token = tokens.get(0);
            String userJson = RedisUtil.get(CacheNames.LOGIN_USER_INFO + token);
            if (userJson != null) {
                List<String> uid = request.getParameterMap().get("uid");
                if (uid != null && uid.size() > 0) {
                    UserAccount account = JSON.parseObject(userJson, UserAccount.class);
                    if (uid.get(0).equals(account.getUserId().toString())) {
                        sec.getUserProperties().put("check", true);
                    }
                }
            }
        }
        super.modifyHandshake(sec, request, response);
    }

}
